package com.zyf.api;

import com.alibaba.fastjson.JSONObject;
import com.zyf.common.excption.YyghException;
import com.zyf.common.result.Result;
import com.zyf.common.result.ResultCodeEnum;
import com.zyf.helper.JwtHelper;
import com.zyf.model.user.UserInfo;
import com.zyf.service.UserinfoService;
import com.zyf.utils.ConstantWxPropertiesUtils;
import com.zyf.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/** 微信登录接口
 * @author zyf
 * @date 2021年05月19日 14:03
 */
@Api("微信操作接口")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeiXinApiController {

    @Autowired
    private UserinfoService userinfoService;

    @ApiOperation(value = "生成微信扫描二维码，返回生成二维码需要的参数")
    @GetMapping("/getLoginParam")
    @ResponseBody
    public Result getLoginParam(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
        map.put("scope", "snsapi_login");
        String redirectUrl = ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL;
        redirectUrl = URLEncoder.encode(redirectUrl, StandardCharsets.UTF_8);
        map.put("response_type", redirectUrl);
        map.put("state",System.currentTimeMillis()+"");
        return Result.ok(map);
    }

    @ApiOperation(value = "微信扫描后进行回调方法")
    @GetMapping("/callback")
    public String callback(String code,String state){
        //第一步 获取临时票据
        System.out.println("code = " +code);
        if (StringUtils.isEmpty(state) || StringUtils.isEmpty(code)) {

            throw new YyghException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
        }
        //拿着code、微信id和密钥，请求微信固定地址，得到两个值
        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessToken = new StringBuffer();
        baseAccessToken.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessToken.toString(),
                ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET, code);
        //使用HttpClientUtils 去请求这个地址
        String accessTokenInfo = null;
        try {
            accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            throw new YyghException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }

        System.out.println("accessTokenInfo = "+accessTokenInfo);
        //字符串返回获取两个值，openId和access_token
        JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
        if(jsonObject.getString("errcode") != null){
            throw new YyghException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }

        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //判断数据库中是否存在微信扫描人的信息， 根据openid判断
        UserInfo userInfo = userinfoService.selectWxInfoOpenid(openid);

        Integer newUser = null;

        if (userInfo ==null){
            //通过openId和access_token 访问微信地址
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
            String resultInfo = null;

            try {
                resultInfo = HttpClientUtils.get(userInfoUrl);
            } catch (Exception e) {
                throw new YyghException(ResultCodeEnum.FETCH_USERINFO_ERROR);
            }

            System.out.println("resultInfo = "+resultInfo);

            //获取用户信息
            JSONObject resultUserInfoJson  = JSONObject.parseObject(resultInfo);
            if(resultUserInfoJson.getString("errcode") != null){
                throw new YyghException(ResultCodeEnum.FETCH_USERINFO_ERROR);
            }

            String nickname = resultUserInfoJson.getString("nickname"); //昵称
            String headimgurl = resultUserInfoJson.getString("headimgurl"); //头像

            //把用户信息存入到数据库中
            userInfo = new UserInfo();
            userInfo.setNickName(nickname).setOpenid(openid).setStatus(1);
            userinfoService.save(userInfo);
        }else if (!StringUtils.isEmpty(userInfo.getPhone())){
            newUser = 1;
        }

        //返回name和token字符串
        HashMap<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }
        map.put("name",name);
        if (StringUtils.isEmpty(userInfo.getPhone())){
            map.put("openid",userInfo.getOpenid());
        }else {
            map.put("openid","");
        }
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);

        //跳转到前端页面
        return "redirect:" + ConstantWxPropertiesUtils.YYGH_BASE_URL + "/weixin/callback?newUser="+newUser+"&token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"), StandardCharsets.UTF_8);

    }

}
